class Snake {
  head: HTMLElement;
  bodies: HTMLCollection;
  snakeContainer: HTMLElement;
  constructor() {
    this.head = document.querySelector('#snake>div')!;
    this.snakeContainer = document.getElementById('snake')!;
    this.bodies = this.snakeContainer.getElementsByTagName('div');
  }
  get HeadX() {
    return this.head.offsetLeft;
  }
  get HeadY() {
    return this.head.offsetTop;
  }
  set HeadX(x: number) {
    if (x < 0 || x > 290) {
      throw new Error("撞墙了!!");
    }
    this.head.style.left = x + 'px';
  }
  set HeadY(y: number) {
    if (y < 0 || y > 290) {
      throw new Error("撞墙了!!");
    }
    this.head.style.top = y + 'px';
  }
  addBody() {
    const body = document.createElement('div');
    this.snakeContainer.appendChild(body);
  }
  moveBody() {
    /* 这里要注意第一个和第二个div会重叠 */
    /* 所以在css中我让蛇头和食物一开始就重叠, 就可以避免吃到第一个食物不会增长的问题 */
    for (let i = this.bodies.length - 1; i > 0; i--) {
      let X = (this.bodies[i - 1] as HTMLElement).offsetLeft;
      let Y = (this.bodies[i - 1] as HTMLElement).offsetTop;
      (this.bodies[i] as HTMLElement).style.left = X + 'px';
      (this.bodies[i] as HTMLElement).style.top = Y + 'px';
    }
  }
}
export default Snake;